package cn.icanci.ladybird.aop;

import cn.icanci.ladybird.common.result.JsonData;
import cn.icanci.ladybird.common.util.cache.GuavaCache;
import com.google.common.cache.Cache;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: icanci
 * @date: Created in 2020/10/17 11:37
 * @classAction: AOP注解解析类 - 配合google的Cache缓存机制 - 之后更改为基于Redis的
 */
@Aspect
@Component
@Slf4j
public class NoRepeatSubmitAop {
    /**
     * 2秒钟的缓存
     */
    private final Cache<String, Object> twoSecondCache = new GuavaCache().getTwoSecondCache();

    @Around("execution(* cn.icanci.ladybird..*Controller.*(..)) && @annotation(nrs)")
    public Object around(ProceedingJoinPoint pjp, NoRepeatSubmit nrs) {
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            String sessionId = RequestContextHolder.getRequestAttributes().getSessionId();
            HttpServletRequest request = requestAttributes.getRequest();
            String key = sessionId + "-" + request.getServletPath();
            if (null == twoSecondCache.getIfPresent(key)) {
                // 缓存中没有这个URL
                Object proceed = pjp.proceed();
                twoSecondCache.put(key, 0);
                return proceed;
            } else {
                log.error("NoRepeatSubmitAop.around - 重复提交");
                return null;
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            log.error("NoRepeatSubmitAop.around - 验证重复提交时出现未知异常");
            return JsonData.builderError("验证重复提交时出现未知异常");
        }
    }
}
